// import Global from '@/global.js';
import { useStore } from 'vuex';

const header = {
  'Content-Type': 'application/json'
}
/**
 * 请求相关的封装
 */
export const baseUrl = "http://localhost:8090/"; // 接口地址 本地环境
// const defaultUserId = "qwertyuiopasdfghjklzxcvbnmqwerty"
const defaultUserId = 1
// export let baseUrl = "https://www.china-baiheng.com/lifetant/dev/api/"; // 开发环境
// export let baseUrl = "https://www.china-baiheng.com/lifetant/prod/api/"; // 生产环境

/**
 * 
 * 封装请求
 * 
 * 
 */
function fetch(options) {
  console.log('fetch options', options)
  if (options.loading) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
  }
  return new Promise((resolve, reject) => {
    const store = useStore()
    // header['userId'] = !store.getters.getUserId ? defaultUserId : store.getters.getUserId
    header['userId'] = !uni.getStorageSync('userId') ? defaultUserId : uni.getStorageSync('userId')
    // header['userId'] = Global.getUserId();
    wx.request({
      url: baseUrl + options.url,
      data: options.data,
      header: header,
      method: options.method,
      success: function(res) {
        if (options.loading) {
          wx.hideLoading()
        }
        if (res.data.code == 1) {
          // 重新登陆
          return false;
        }
        if (res.data.code != 200) {
          // wx.showToast({
          //   title: res.data.msg,
          //   mask: "true",
          //   icon: 'none',
          //   duration: 3000
          // })
          // return;
        }
        resolve(res.data); //把请求到的数据发到引用请求的地方
      },
      fail: function(err) {
        if (options.loading) {
          wx.hideLoading()
        }
        reject(err)
        wx.showToast({
          title: "网络连接超时",
          icon: 'none',
          duration: 3000,
        })
      }
    })
  })
}
/**
 * POST 请求
 */
export function post(url, params, loading = true) {
  console.log(params, loading);
  var option = {
    url: url,
    data: params,
    method: 'POST',
    loading
  }
  return fetch(option);
}

/**
 * GET请求
 */
export function get(urls, params, loading = true) {
  console.log(params, loading);
  var option = {
    url: urls,
    data: params,
    method: 'GET',
    loading
  }
  return fetch(option);
}

export const CustRequest = {
  get,
  post,
  fetch,
  baseUrl,
  defaultUserId
}